package com.ctgu.frequence.step3;

import com.ctgu.frequence.Utils.ValueComparator;

import java.util.*;

public class CountPhrase {
    public static void countPhrase(String str,int n){
        //将文本字符串分割
        String[] list = str.split("[^a-zA-Z0-9\\s]+");
        Map<String,Integer> map = new HashMap<String,Integer>(); // 定义一个哈希表
        int sum = 0; //统计短语总数
        for (int i = 0; i < list.length; i++) {
            //筛选长度为n的短语
            list[i] = list[i].trim();
            list[i].replaceAll("\\n\\r"," ");
            String[] s = list[i].split("\\s+");
            if(s.length != n){
                continue;
            }
            if(!map.containsKey(list[i])){
                map.put(list[i], 1);
            }else{
                Integer num = map.get(list[i]);//有就增1
                map.put(list[i], num + 1);
            }
            sum++;
        }
        //对map进行排序
        List<Map.Entry<String,Integer>> ls=new ArrayList<>();
        ls.addAll(map.entrySet());
        ValueComparator vc=new ValueComparator();
        Collections.sort(ls,vc);
        for(Map.Entry<String, Integer> item:ls){
            double per = 1.0 * item.getValue() / sum * 100;
            System.out.printf("%s：%.2f%%\n",item.getKey(),per);
        }
    }
}
